<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 老猫 <thinkcmf@126.com>
// +----------------------------------------------------------------------
namespace app\goods\controller;

use cmf\controller\HomeBaseController;
use app\goods\model\GoodsCategoryModel;
use app\goods\service\GoodsService;
use app\goods\model\PortalPostModel;
use think\Db;

class DetailsController extends HomeBaseController
{
    public function index()
    {

        $goodsCategoryModel = new GoodsCategoryModel();
        $goodsService       = new GoodsService();

        $goodsId    = $this->request->param('id', 0, 'intval');
        $categoryId = $this->request->param('cid', 0, 'intval');
        $goods      = $goodsService->publishedGoods($goodsId, $categoryId);

        if (empty($goodsId)) {
            abort(404, '产品不存在!');
        }

        $tplName = 'details';

        if (empty($categoryId)) {
            $categories = $goods['categories'];

            if (count($categories) > 0) {
                $this->assign('category', $categories[0]);
            } else {
                abort(404, '产品未指定分类!');
            }

        } else {
            $category = $goodsCategoryModel->where('id', $categoryId)->where('is_show', 1)->find();

            if (empty($category)) {
                abort(404, '产品不存在!');
            }

            $this->assign('category', $category);

            $tplName = empty($category["one_tpl"]) ? $tplName : $category["one_tpl"];
        }

        //访问量统计
        Db::name('goods')->where(['goods_id' => $goodsId])->setInc('post_hits');
        // checkVisit($goodsId,3);

        // hook('goods_before_assign_article', $goods);

        $this->assign('cid', $categoryId);
        $this->assign('goods', $goods);
        // $this->assign('prev_article', $prevGoods);
        // $this->assign('next_article', $nextGoods);

        $tplName = empty($goods['more']['template']) ? $tplName : $goods['more']['template'];

        return $this->fetch("/$tplName");
    }

    // 产品点赞
    public function doLike()
    {
        $this->checkUserLogin();
        $goodsId = $this->request->param('id', 0, 'intval');


        $canLike = cmf_check_user_action("posts$goodsId", 1);

        if ($canLike) {
            Db::name('goods_post')->where(['id' => $goodsId])->setInc('post_like');

            $this->success("赞好啦！");
        } else {
            $this->error("您已赞过啦！");
        }
    }

    public function myIndex()
    {
        //获取登录会员信息
        $user = cmf_get_current_user();
        $this->assign('user_id', $user['id']);
        return $this->fetch('user/index');
    }

    //用户添加
    public function add()
    {
        return $this->fetch('user/add');
    }

    public function addPost()
    {
        if ($this->request->isPost()) {
            $data   = $this->request->param();
            $post   = $data['post'];
            $result = $this->validate($post, 'AdminGoods');
            if ($result !== true) {
                $this->error($result);
            }

            $goodsPostModel = new PortalPostModel();

            if (!empty($data['photo_names']) && !empty($data['photo_urls'])) {
                $data['post']['more']['photos'] = [];
                foreach ($data['photo_urls'] as $key => $url) {
                    $photoUrl = cmf_asset_relative_url($url);
                    array_push($data['post']['more']['photos'], ["url" => $photoUrl, "name" => $data['photo_names'][$key]]);
                }
            }

            if (!empty($data['file_names']) && !empty($data['file_urls'])) {
                $data['post']['more']['files'] = [];
                foreach ($data['file_urls'] as $key => $url) {
                    $fileUrl = cmf_asset_relative_url($url);
                    array_push($data['post']['more']['files'], ["url" => $fileUrl, "name" => $data['file_names'][$key]]);
                }
            }
            $goodsPostModel->adminAddGoods($data['post'], $data['post']['categories']);

            $this->success('添加成功!', url('Goods/myIndex', ['id' => $goodsPostModel->id]));
        }
    }

    public function select()
    {
        $ids                 = $this->request->param('ids');
        $selectedIds         = explode(',', $ids);
        $goodsCategoryModel = new GoodsCategoryModel();

        $tpl = <<<tpl
<tr class='data-item-tr'>
    <td>
        <input type='checkbox' class='js-check' data-yid='js-check-y' data-xid='js-check-x' name='ids[]'
                               value='\$id' data-name='\$name' \$checked>
    </td>
    <td>\$id</td>
    <td>\$spacer <a href='\$url' target='_blank'>\$name</a></td>
    <td>\$description</td>
</tr>
tpl;

        $categoryTree = $goodsCategoryModel->adminCategoryTableTree($selectedIds, $tpl);

        $where      = ['delete_time' => 0];
        $categories = $goodsCategoryModel->where($where)->select();

        $this->assign('categories', $categories);
        $this->assign('selectedIds', $selectedIds);
        $this->assign('categories_tree', $categoryTree);
        return $this->fetch('user/select');
    }
}
